{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| default_exp models.tide"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TiDE\n",
    "> Time-series Dense Encoder (`TiDE`) is a MLP-based univariate time-series forecasting model. `TiDE` uses Multi-layer Perceptrons (MLPs) in an encoder-decoder model for long-term time-series forecasting. In addition, this model can handle exogenous inputs.\n",
    "\n",
    "<br><br>**References**<br>-[Das, Abhimanyu, Weihao Kong, Andrew Leach, Shaan Mathur, Rajat Sen, and Rose Yu (2024). \"Long-term Forecasting with TiDE: Time-series Dense Encoder.\"](http://arxiv.org/abs/2304.08424)<br>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![Figure 1. TiDE architecture.](imgs_models/tide.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "import logging\n",
    "import warnings\n",
    "from fastcore.test import test_eq\n",
    "from nbdev.showdoc import show_doc\n",
    "from neuralforecast.common._model_checks import check_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "from typing import Optional\n",
    "\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "from neuralforecast.losses.pytorch import MAE\n",
    "from neuralforecast.common._base_model import BaseModel"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Auxiliary Functions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.1 MLP residual\n",
    "An MLP block with a residual connection."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class MLPResidual(nn.Module):\n",
    "    \"\"\"\n",
    "    MLPResidual\n",
    "    \"\"\"   \n",
    "    def __init__(self, input_dim, hidden_size, output_dim, dropout, layernorm):\n",
    "        super().__init__()\n",
    "        self.layernorm = layernorm\n",
    "        if layernorm:\n",
    "            self.norm = nn.LayerNorm(output_dim)\n",
    "\n",
    "        self.drop = nn.Dropout(dropout)\n",
    "        self.lin1 = nn.Linear(input_dim, hidden_size)\n",
    "        self.lin2 = nn.Linear(hidden_size, output_dim)\n",
    "        self.skip = nn.Linear(input_dim, output_dim)\n",
    "\n",
    "    def forward(self, input):\n",
    "        # MLP dense\n",
    "        x = F.relu(self.lin1(input))                                            \n",
    "        x = self.lin2(x)\n",
    "        x = self.drop(x)\n",
    "\n",
    "        # Skip connection\n",
    "        x_skip = self.skip(input)\n",
    "\n",
    "        # Combine\n",
    "        x = x + x_skip\n",
    "\n",
    "        if self.layernorm:\n",
    "            return self.norm(x)\n",
    "\n",
    "        return x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| export\n",
    "class TiDE(BaseModel):\n",
    "    \"\"\" TiDE\n",
    "\n",
    "    Time-series Dense Encoder (`TiDE`) is a MLP-based univariate time-series forecasting model. `TiDE` uses Multi-layer Perceptrons (MLPs) in an encoder-decoder model for long-term time-series forecasting.\n",
    "\n",
    "    **Parameters:**<br>\n",
    "    `h`: int, forecast horizon.<br>\n",
    "    `input_size`: int, considered autorregresive inputs (lags), y=[1,2,3,4] input_size=2 -> lags=[1,2].<br>\n",
    "    `hidden_size`: int=1024, number of units for the dense MLPs.<br>\n",
    "    `decoder_output_dim`: int=32, number of units for the output of the decoder.<br>\n",
    "    `temporal_decoder_dim`: int=128, number of units for the hidden sizeof the temporal decoder.<br>\n",
    "    `dropout`: float=0.0, dropout rate between (0, 1) .<br>\n",
    "    `layernorm`: bool=True, if True uses Layer Normalization on the MLP residual block outputs.<br>\n",
    "    `num_encoder_layers`: int=1, number of encoder layers.<br>\n",
    "    `num_decoder_layers`: int=1, number of decoder layers.<br>\n",
    "    `temporal_width`: int=4, lower temporal projected dimension.<br>\n",
    "    `futr_exog_list`: str list, future exogenous columns.<br>\n",
    "    `hist_exog_list`: str list, historic exogenous columns.<br>\n",
    "    `stat_exog_list`: str list, static exogenous columns.<br>    \n",
    "    `exclude_insample_y`: bool=False, whether to exclude the target variable from the historic exogenous data.<br>\n",
    "    `loss`: PyTorch module, instantiated train loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `valid_loss`: PyTorch module=`loss`, instantiated valid loss class from [losses collection](https://nixtla.github.io/neuralforecast/losses.pytorch.html).<br>\n",
    "    `max_steps`: int=1000, maximum number of training steps.<br>\n",
    "    `learning_rate`: float=1e-3, Learning rate between (0, 1).<br>\n",
    "    `num_lr_decays`: int=-1, Number of learning rate decays, evenly distributed across max_steps.<br>\n",
    "    `early_stop_patience_steps`: int=-1, Number of validation iterations before early stopping.<br>\n",
    "    `val_check_steps`: int=100, Number of training steps between every validation loss check.<br>\n",
    "    `batch_size`: int=32, number of different series in each batch.<br>\n",
    "    `valid_batch_size`: int=None, number of different series in each validation and test batch.<br>\n",
    "    `windows_batch_size`: int=1024, number of windows to sample in each training batch, default uses all.<br>\n",
    "    `inference_windows_batch_size`: int=1024, number of windows to sample in each inference batch, -1 uses all.<br>\n",
    "    `start_padding_enabled`: bool=False, if True, the model will pad the time series with zeros at the beginning, by input size.<br>\n",
    "    `step_size`: int=1, step size between each window of temporal data.<br>\n",
    "    `scaler_type`: str='identity', type of scaler for temporal inputs normalization see [temporal scalers](https://nixtla.github.io/neuralforecast/common.scalers.html).<br>\n",
    "    `random_seed`: int=1, random_seed for pytorch initializer and numpy generators.<br>\n",
    "    `drop_last_loader`: bool=False, if True `TimeSeriesDataLoader` drops last non-full batch.<br>\n",
    "    `alias`: str, optional,  Custom name of the model.<br>\n",
    "    `optimizer`: Subclass of 'torch.optim.Optimizer', optional, user specified optimizer instead of the default choice (Adam).<br>\n",
    "    `optimizer_kwargs`: dict, optional, list of parameters used by the user specified `optimizer`.<br>\n",
    "    `lr_scheduler`: Subclass of 'torch.optim.lr_scheduler.LRScheduler', optional, user specified lr_scheduler instead of the default choice (StepLR).<br>\n",
    "    `lr_scheduler_kwargs`: dict, optional, list of parameters used by the user specified `lr_scheduler`.<br>\n",
    "    `dataloader_kwargs`: dict, optional, list of parameters passed into the PyTorch Lightning dataloader by the `TimeSeriesDataLoader`. <br>\n",
    "    `**trainer_kwargs`: int,  keyword trainer arguments inherited from [PyTorch Lighning's trainer](https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.trainer.trainer.Trainer.html?highlight=trainer).<br>    \n",
    "\n",
    "    **References:**<br>\n",
    "    - [Das, Abhimanyu, Weihao Kong, Andrew Leach, Shaan Mathur, Rajat Sen, and Rose Yu (2024). \"Long-term Forecasting with TiDE: Time-series Dense Encoder.\"](http://arxiv.org/abs/2304.08424)\n",
    "\n",
    "    \"\"\"\n",
    "    # Class attributes\n",
    "    EXOGENOUS_FUTR = True\n",
    "    EXOGENOUS_HIST = True\n",
    "    EXOGENOUS_STAT = True \n",
    "    MULTIVARIATE = False    # If the model produces multivariate forecasts (True) or univariate (False)\n",
    "    RECURRENT = False       # If the model produces forecasts recursively (True) or direct (False)\n",
    "\n",
    "    def __init__(self,\n",
    "                 h,\n",
    "                 input_size,   \n",
    "                 hidden_size = 512,\n",
    "                 decoder_output_dim = 32,\n",
    "                 temporal_decoder_dim = 128,\n",
    "                 dropout = 0.3,\n",
    "                 layernorm=True,\n",
    "                 num_encoder_layers = 1,\n",
    "                 num_decoder_layers = 1,\n",
    "                 temporal_width = 4,\n",
    "                 futr_exog_list = None,\n",
    "                 hist_exog_list = None,\n",
    "                 stat_exog_list = None,\n",
    "                 exclude_insample_y = False,\n",
    "                 loss = MAE(),\n",
    "                 valid_loss = None,\n",
    "                 max_steps: int = 1000,\n",
    "                 learning_rate: float = 1e-3,\n",
    "                 num_lr_decays: int = -1,\n",
    "                 early_stop_patience_steps: int =-1,\n",
    "                 val_check_steps: int = 100,\n",
    "                 batch_size: int = 32,\n",
    "                 valid_batch_size: Optional[int] = None,\n",
    "                 windows_batch_size = 1024,\n",
    "                 inference_windows_batch_size = 1024,\n",
    "                 start_padding_enabled = False,\n",
    "                 step_size: int = 1,\n",
    "                 scaler_type: str = 'identity',\n",
    "                 random_seed: int = 1,\n",
    "                 drop_last_loader: bool = False,\n",
    "                 alias: Optional[str] = None,\n",
    "                 optimizer = None,\n",
    "                 optimizer_kwargs = None,\n",
    "                 lr_scheduler = None,\n",
    "                 lr_scheduler_kwargs = None,\n",
    "                 dataloader_kwargs = None,\n",
    "                 **trainer_kwargs):\n",
    "\n",
    "        # Inherit BaseWindows class\n",
    "        super(TiDE, self).__init__(\n",
    "            h=h,\n",
    "            input_size=input_size,\n",
    "            futr_exog_list=futr_exog_list,\n",
    "            hist_exog_list=hist_exog_list,\n",
    "            stat_exog_list=stat_exog_list,\n",
    "            exclude_insample_y = exclude_insample_y,\n",
    "            loss=loss,\n",
    "            valid_loss=valid_loss,\n",
    "            max_steps=max_steps,\n",
    "            learning_rate=learning_rate,\n",
    "            num_lr_decays=num_lr_decays,\n",
    "            early_stop_patience_steps=early_stop_patience_steps,\n",
    "            val_check_steps=val_check_steps,\n",
    "            batch_size=batch_size,\n",
    "            valid_batch_size=valid_batch_size,\n",
    "            windows_batch_size=windows_batch_size,\n",
    "            inference_windows_batch_size=inference_windows_batch_size,\n",
    "            start_padding_enabled=start_padding_enabled,\n",
    "            step_size=step_size,\n",
    "            scaler_type=scaler_type,\n",
    "            random_seed=random_seed,\n",
    "            drop_last_loader=drop_last_loader,\n",
    "            alias=alias,\n",
    "            optimizer=optimizer,\n",
    "            optimizer_kwargs=optimizer_kwargs,\n",
    "            lr_scheduler=lr_scheduler,\n",
    "            lr_scheduler_kwargs=lr_scheduler_kwargs,\n",
    "            dataloader_kwargs=dataloader_kwargs,\n",
    "            **trainer_kwargs\n",
    "        )   \n",
    "        self.h = h\n",
    "\n",
    "        if self.hist_exog_size > 0 or self.futr_exog_size > 0:\n",
    "            self.hist_exog_projection = MLPResidual(input_dim = self.hist_exog_size,\n",
    "                                                    hidden_size=hidden_size,\n",
    "                                                        output_dim=temporal_width,\n",
    "                                                        dropout=dropout,\n",
    "                                                        layernorm=layernorm)  \n",
    "        if self.futr_exog_size > 0:\n",
    "            self.futr_exog_projection = MLPResidual(input_dim = self.futr_exog_size,\n",
    "                                                    hidden_size = hidden_size,\n",
    "                                                    output_dim=temporal_width,\n",
    "                                                    dropout=dropout,\n",
    "                                                    layernorm=layernorm)\n",
    "\n",
    "        # Encoder\n",
    "        dense_encoder_input_size = input_size + \\\n",
    "                                    input_size * (self.hist_exog_size > 0) * temporal_width + \\\n",
    "                                    (input_size + h) * (self.futr_exog_size > 0) * temporal_width + \\\n",
    "                                    (self.stat_exog_size > 0) * self.stat_exog_size\n",
    "\n",
    "        dense_encoder_layers = [MLPResidual(input_dim=dense_encoder_input_size if i == 0 else hidden_size,\n",
    "                                            hidden_size=hidden_size,\n",
    "                                          output_dim=hidden_size,\n",
    "                                          dropout=dropout,\n",
    "                                          layernorm=layernorm) for i in range(num_encoder_layers)]\n",
    "        self.dense_encoder = nn.Sequential(*dense_encoder_layers)\n",
    "\n",
    "        # Decoder\n",
    "        decoder_output_size = decoder_output_dim * h\n",
    "        dense_decoder_layers = [MLPResidual(input_dim=hidden_size,\n",
    "                                            hidden_size=hidden_size,\n",
    "                                          output_dim=decoder_output_size if i == num_decoder_layers - 1 else hidden_size,\n",
    "                                          dropout=dropout,\n",
    "                                          layernorm=layernorm) for i in range(num_decoder_layers)]\n",
    "        self.dense_decoder = nn.Sequential(*dense_decoder_layers)\n",
    "\n",
    "        # Temporal decoder with loss dependent dimensions\n",
    "        self.temporal_decoder = MLPResidual(input_dim = decoder_output_dim + (self.futr_exog_size > 0) * temporal_width,\n",
    "                                            hidden_size = temporal_decoder_dim,\n",
    "                                          output_dim=self.loss.outputsize_multiplier,\n",
    "                                          dropout=dropout,\n",
    "                                          layernorm=layernorm)\n",
    "\n",
    "\n",
    "        # Global skip connection\n",
    "        self.global_skip = nn.Linear(in_features = input_size,\n",
    "                                     out_features = h * self.loss.outputsize_multiplier)\n",
    "\n",
    "    def forward(self, windows_batch):\n",
    "        # Parse windows_batch\n",
    "        x             = windows_batch['insample_y']                     #   [B, L, 1]\n",
    "        hist_exog     = windows_batch['hist_exog']                      #   [B, L, X]\n",
    "        futr_exog     = windows_batch['futr_exog']                      #   [B, L + h, F]\n",
    "        stat_exog     = windows_batch['stat_exog']                      #   [B, S]\n",
    "        batch_size, seq_len = x.shape[:2]                               #   B = batch_size, L = seq_len\n",
    "\n",
    "        # Flatten insample_y\n",
    "        x = x.reshape(batch_size, -1)                                   #   [B, L, 1] -> [B, L]\n",
    "\n",
    "        # Global skip connection\n",
    "        x_skip = self.global_skip(x)                                    #   [B, L] -> [B, h * n_outputs]\n",
    "        x_skip = x_skip.reshape(batch_size, self.h, -1)                 #   [B, h * n_outputs] -> [B, h, n_outputs]\n",
    "\n",
    "        # Concatenate x with flattened historical exogenous\n",
    "        if self.hist_exog_size > 0:\n",
    "            x_hist_exog = self.hist_exog_projection(hist_exog)          #   [B, L, X] -> [B, L, temporal_width]\n",
    "            x_hist_exog = x_hist_exog.reshape(batch_size, -1)           #   [B, L, temporal_width] -> [B, L * temporal_width]\n",
    "            x = torch.cat((x, x_hist_exog), dim=1)                      #   [B, L] + [B, L * temporal_width] -> [B, L * (1 + temporal_width)]\n",
    "\n",
    "        # Concatenate x with flattened future exogenous\n",
    "        if self.futr_exog_size > 0:\n",
    "            x_futr_exog = self.futr_exog_projection(futr_exog)          #   [B, L + h, F] -> [B, L + h, temporal_width]\n",
    "            x_futr_exog_flat = x_futr_exog.reshape(batch_size, -1)      #   [B, L + h, temporal_width] -> [B, (L + h) * temporal_width]\n",
    "            x = torch.cat((x, x_futr_exog_flat), dim=1)                 #   [B, L * (1 + temporal_width)] + [B, (L + h) * temporal_width] -> [B, L * (1 + 2 * temporal_width) + h * temporal_width]\n",
    "\n",
    "        # Concatenate x with static exogenous\n",
    "        if self.stat_exog_size > 0:\n",
    "            x = torch.cat((x, stat_exog), dim=1)                        #   [B, L * (1 + 2 * temporal_width) + h * temporal_width] + [B, S] -> [B, L * (1 + 2 * temporal_width) + h * temporal_width + S]\n",
    "\n",
    "        # Dense encoder\n",
    "        x = self.dense_encoder(x)                                       #   [B, L * (1 + 2 * temporal_width) + h * temporal_width + S] -> [B, hidden_size]\n",
    "\n",
    "        # Dense decoder\n",
    "        x = self.dense_decoder(x)                                       #   [B, hidden_size] ->  [B, decoder_output_dim * h]\n",
    "        x = x.reshape(batch_size, self.h, -1)                           #   [B, decoder_output_dim * h] -> [B, h, decoder_output_dim]\n",
    "\n",
    "        # Stack with futr_exog for horizon part of futr_exog\n",
    "        if self.futr_exog_size > 0:\n",
    "            x_futr_exog_h = x_futr_exog[:, seq_len:]                    #  [B, L + h, temporal_width] -> [B, h, temporal_width]\n",
    "            x = torch.cat((x, x_futr_exog_h), dim=2)                    #  [B, h, decoder_output_dim] + [B, h, temporal_width] -> [B, h, temporal_width + decoder_output_dim]\n",
    "\n",
    "        # Temporal decoder\n",
    "        x = self.temporal_decoder(x)                                    #  [B, h, temporal_width + decoder_output_dim] -> [B, h, n_outputs]\n",
    "\n",
    "        forecast = x + x_skip\n",
    "        \n",
    "        return forecast\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(TiDE)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(TiDE.fit, name='TiDE.fit')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "show_doc(TiDE.predict, name='TiDE.predict')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| hide\n",
    "# Unit tests for models\n",
    "logging.getLogger(\"pytorch_lightning\").setLevel(logging.ERROR)\n",
    "logging.getLogger(\"lightning_fabric\").setLevel(logging.ERROR)\n",
    "with warnings.catch_warnings():\n",
    "    warnings.simplefilter(\"ignore\")\n",
    "    check_model(TiDE, [\"airpassengers\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Usage Examples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#| eval: false\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from neuralforecast import NeuralForecast\n",
    "from neuralforecast.models import TiDE\n",
    "from neuralforecast.losses.pytorch import GMM\n",
    "from neuralforecast.utils import AirPassengersPanel, AirPassengersStatic\n",
    "\n",
    "Y_train_df = AirPassengersPanel[AirPassengersPanel.ds<AirPassengersPanel['ds'].values[-12]] # 132 train\n",
    "Y_test_df = AirPassengersPanel[AirPassengersPanel.ds>=AirPassengersPanel['ds'].values[-12]].reset_index(drop=True) # 12 test\n",
    "\n",
    "fcst = NeuralForecast(\n",
    "    models=[\n",
    "            TiDE(h=12,\n",
    "                input_size=24,\n",
    "                loss=GMM(n_components=7, return_params=True, level=[80,90], weighted=True),\n",
    "                max_steps=100,\n",
    "                scaler_type='standard',\n",
    "                futr_exog_list=['y_[lag12]'],\n",
    "                hist_exog_list=None,\n",
    "                stat_exog_list=['airline1'],\n",
    "                ),     \n",
    "    ],\n",
    "    freq='ME'\n",
    ")\n",
    "fcst.fit(df=Y_train_df, static_df=AirPassengersStatic)\n",
    "forecasts = fcst.predict(futr_df=Y_test_df)\n",
    "\n",
    "# Plot quantile predictions\n",
    "Y_hat_df = forecasts.reset_index(drop=False).drop(columns=['unique_id','ds'])\n",
    "plot_df = pd.concat([Y_test_df, Y_hat_df], axis=1)\n",
    "plot_df = pd.concat([Y_train_df, plot_df])\n",
    "\n",
    "plot_df = plot_df[plot_df.unique_id=='Airline1'].drop('unique_id', axis=1)\n",
    "plt.plot(plot_df['ds'], plot_df['y'], c='black', label='True')\n",
    "plt.plot(plot_df['ds'], plot_df['TiDE-median'], c='blue', label='median')\n",
    "plt.fill_between(x=plot_df['ds'][-12:], \n",
    "                 y1=plot_df['TiDE-lo-90'][-12:].values,\n",
    "                 y2=plot_df['TiDE-hi-90'][-12:].values,\n",
    "                 alpha=0.4, label='level 90')\n",
    "plt.legend()\n",
    "plt.grid()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
